#include <jnicallbackhelper.h>
#include <compressorConfigure.h>

jnicallbackhelper::jnicallbackhelper(JavaVM *jvm, JNIEnv *env, jobject jobj) {
    this->jvm = jvm;
    this->env = env;
    //object不能跨线程使用，必须晋升为全局对象
    this->jobj = env->NewGlobalRef(jobj);
    jclass cls = env->GetObjectClass(this->jobj);
    jmethodId = env->GetMethodID(cls, "onCompressorForNative",
                                 "(Landroid/graphics/Bitmap;Ljava/lang/String;)V");
}

jnicallbackhelper::~jnicallbackhelper() {
    jvm = nullptr;
    jmethodId = nullptr;
    env->DeleteGlobalRef(jobj);
    jobj = nullptr;
    env = nullptr;
}


void jnicallbackhelper::onResult(int thread_mode, jobject raw, const char *outPutPath) {
    if (thread_mode == THREAD_MAIN) {
        if (DEBUG) LOG_DEBUG("原有线程回调 图片地址：%s", outPutPath);
        jstring result = env->NewStringUTF(outPutPath);
        env->CallVoidMethod(jobj, jmethodId, raw, result);
        env->ReleaseStringUTFChars(result, outPutPath);
    } else {
        if (DEBUG) LOG_DEBUG("子线程中回调 图片地址：%s", outPutPath);
        //子线程原有env不可用
        JNIEnv *env_child;
        jvm->AttachCurrentThread(&env_child, nullptr);
        jstring result = env_child->NewStringUTF(outPutPath);
        env_child->CallVoidMethod(jobj, jmethodId, raw, result);
        env_child->ReleaseStringUTFChars(result, outPutPath);
        jvm->DetachCurrentThread();
    }
}
